package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.itheima.common.DefaultException;
import com.itheima.common.Paging;
import com.itheima.config.RabbitMQConfig;
import com.itheima.convert.MessageConvert;
import com.itheima.dto.message.MessageDto;
import com.itheima.dto.message.MessagePageDto;
import com.itheima.entity.*;
import com.itheima.enums.MqOperationEnum;
import com.itheima.enums.OrganizationEnum;
import com.itheima.enums.RedisEnum;
import com.itheima.mapper.MessageLinkKindMapper;
import com.itheima.mapper.MessageMapper;
import com.itheima.service.*;
import com.itheima.utils.CheckUtil;
import com.itheima.utils.OssUtil;
import com.itheima.utils.PageUtils;
import com.itheima.vo.KindVo;
import com.itheima.vo.message.MessageBoardVo;
import com.itheima.vo.message.MessageSoaringVo;
import com.itheima.vo.message.MessageVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 51585
 * @description 针对表【message】的数据库操作Service实现
 * @createDate 2022-10-01 22:00:51
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message>
        implements MessageService {

    @Resource
    private MessageService messageService;

    @Resource
    private MessageLinkUserService messageLinkUserService;

    @Resource
    private OssUtil ossUtil;
    @Resource
    private MessageLinkKindService messageLinkKindService;
    @Resource
    private MessageMapper messageMapper;
    @Resource
    private MessageLinkKindMapper messageLinkKindMapper;
    @Resource
    private MessageConvert messageConvert;
    @Resource
    private SensitiveWordFilterService sensitiveWordFilterService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private KindService kindService;
    @Resource
    private UserLikeMessageService userLikeMessageService;
    @Resource
    private UserService userService;

    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    @Override
    public void sendMessage(MessageDto messageDto) throws Exception {
        String userId = CheckUtil.checkLogin();
        filterMessageDto(messageDto);
        Message message = messageConvert.messageDtoToMessage(messageDto, userId, LocalDateTime.now());
        saveMessage(message);
        saveMessageLinkKind(messageDto, message);
        saveMessageLinkUser(messageDto, message);
    }

    @Override
    public Paging<MessageVo> pageMessage(MessagePageDto messagePageDto) throws Exception {
        // 筛选符合要求的信息
        String userId = CheckUtil.checkLogin();
//        String userId = "19251104252";
        Page<?> page = new Page<>(messagePageDto.getPageIndex(), messagePageDto.getPageSize());
        User user = userService.getById(userId);
        IPage<MessageVo> iPage;
        if (user.getOrganizationId().equals(OrganizationEnum.administrators.getOrganizationId()) ||
                user.getOrganizationId().equals(OrganizationEnum.school.getOrganizationId())) {
            iPage = messageMapper.pageAllMessage(page, messagePageDto);
        }else {
            iPage = messageMapper.pageMessage(page, messagePageDto, userId);
        }
        iPage.getRecords().forEach(messageVo -> {
            Integer messageVoId = messageVo.getId();
            // 补充种类信息
            List<Integer> kinds = messageLinkKindMapper.showKind(messageVoId);
            messageVo.setKinds(kinds);
            supplyLikeStatus(messageVo, userId, messageVoId);
            // 查看redis中是否有新数据，有的话使用redis的数据
            Long rank = redisTemplate.opsForZSet().rank(RedisEnum.MESSAGE_LIKES.getRedis(), messageVoId);
            Optional.ofNullable(rank).ifPresent(k -> {
                messageVo.setLikeCount(redisTemplate.opsForZSet().score(RedisEnum.MESSAGE_LIKES.getRedis(),messageVoId).intValue());
            });
        });

        return PageUtils.toPage(iPage);
    }

    /**
     * 补充自己对信息的点赞状态
     *
     * @param vo        返回信息vo
     * @param userId    用户id
     * @param messageId 信息id
     */
    public void supplyLikeStatus(MessageVo vo, String userId, Integer messageId) {
        UserLikeMessage one = userLikeMessageService.lambdaQuery()
                .select(UserLikeMessage::getStatus)
                .eq(UserLikeMessage::getUserId, userId)
                .eq(UserLikeMessage::getMessageId, messageId)
                .isNull(UserLikeMessage::getDeletedAt)
                .one();
        UserLikeMessage mid = new UserLikeMessage();
        mid.setStatus(0);
        UserLikeMessage res = Optional.ofNullable(one).orElse(mid);
        vo.setLikeStatus(res.getStatus());
    }

    @Override
    public Paging<MessageVo> pagePersonalMessage(MessagePageDto messagePageDto) throws Exception {
        String userId = CheckUtil.checkLogin();
//        String userId = "19251104252";
        Page<?> page = new Page<>(messagePageDto.getPageIndex(), messagePageDto.getPageSize());
        IPage<MessageVo> messageVoIPage = messageMapper.pagePersonalMessage(page, messagePageDto, userId);
        messageVoIPage.getRecords().forEach(messageVo -> {
            Integer id = messageVo.getId();
            // 加入当前信息的种类
            messageVo.setKinds(messageLinkKindMapper.showKind(id));
            supplyLikeStatus(messageVo, userId, messageVo.getId());
            // 查看redis中是否有新数据，有的话使用redis的数据
            Long rank = redisTemplate.opsForZSet().rank(RedisEnum.MESSAGE_LIKES.getRedis(), id);
            Optional.ofNullable(rank).ifPresent(k->{
                messageVo.setLikeCount(redisTemplate.opsForZSet().score(RedisEnum.MESSAGE_LIKES.getRedis(),id).intValue());
            });
        });
        return PageUtils.toPage(messageVoIPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deleteMessage(List<Integer> messageIds) throws Exception {
        String userId = CheckUtil.checkLogin();
//        String userId = "19251104253";
        checkPower(userId, messageIds);
        doDelete(messageIds);
        messageIds.forEach(k->{
            redisTemplate.opsForZSet().remove(RedisEnum.MESSAGE_LIKES.getRedis(), k);
            redisTemplate.opsForZSet().remove(RedisEnum.MESSAGE_LIKE_HISTORY.getRedis(),k);
            redisTemplate.delete(RedisEnum.USER_LIKE_MESSAGE.getRedis() + k);
        });
        return "删除成功";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void likeMessage(Integer messageId) throws Exception {
        String userId = CheckUtil.checkLogin();
//        String userId = "19251104252";
        operateUserLikeMessage(messageId, userId);
    }

    @Override
    public void cancelLikeMessage(Integer messageId) throws Exception {
        String userId = CheckUtil.checkLogin();
//        String userId = "19251104252";
        cancelUserLikeMessage(messageId, userId);

    }

    @Override
    public void syncLikeMessage() {
        Set<Integer> range = redisTemplate.opsForZSet().range(RedisEnum.MESSAGE_LIKES.getRedis(), 0, -1);
        Map<Integer, Integer> map = new HashMap<>(range.size());
        range.forEach(id -> {
            Integer score = redisTemplate.opsForZSet().score(RedisEnum.MESSAGE_LIKES.getRedis(), id).intValue();
            map.put(id, score);
        });
        checkLikeCount(map);
        List<Message> collect = range.stream().map(messageId -> {
            Message message = new Message();
            message.setId(messageId);
            message.setLikeCount(map.get(messageId));
            message.setUpdatedAt(LocalDateTime.now());
            return message;
        }).collect(Collectors.toList());
        messageService.updateBatchById(collect);
        supplySurplusLikeCount(range);
    }

    /**
     * 补充新闻点赞信息进入redis
     *
     * @param range redis中已有的新闻id
     */
    public void supplySurplusLikeCount(Set<Integer> range) {
        List<Message> list = this.lambdaQuery()
                .select(Message::getId, Message::getLikeCount)
                .notIn(Message::getId, range)
                .isNull(Message::getDeletedAt)
                .list();
        Map<Integer, Integer> map = list.stream().collect(Collectors.toMap(Message::getId, Message::getLikeCount));
        map.forEach((k, v) -> {
            redisTemplate.opsForZSet().add(RedisEnum.MESSAGE_LIKES.getRedis(), k, v);
        });
    }

    /**
     * 统计信息的点赞总数，以数据库的为准
     *
     * @param map messageId和点赞数的map集合
     */
    public void checkLikeCount(Map<Integer, Integer> map) {
        map.forEach((k, v) -> {
            Integer likeCount = userLikeMessageService.lambdaQuery()
                    .eq(UserLikeMessage::getMessageId, k)
                    .eq(UserLikeMessage::getStatus, 1)
                    .isNull(UserLikeMessage::getDeletedAt)
                    .count();
            if (!v.equals(likeCount)) {
                redisTemplate.opsForZSet().remove(RedisEnum.MESSAGE_LIKES.getRedis(), k);
                redisTemplate.opsForZSet().add(RedisEnum.MESSAGE_LIKES.getRedis(), k, likeCount);
            }
        });
    }

    @Override
    public List<KindVo> findKind() {
        List<Kind> list = kindService.lambdaQuery()
                .select(Kind::getId, Kind::getType)
                .isNull(Kind::getDeletedAt)
                .list();
        return messageConvert.toKindVoList(list);
    }

    @Override
    public void addKind(String type) throws Exception {
        String userId = CheckUtil.checkLogin();
        User user = userService.getById(userId);
        if (!user.getOrganizationId().equals(OrganizationEnum.administrators.getOrganizationId())
                && !user.getOrganizationId().equals(OrganizationEnum.school.getOrganizationId())) {
            throw new DefaultException("没有权限");
        }
        Kind mid = kindService.lambdaQuery()
                .select(Kind::getId)
                .eq(Kind::getType, type)
                .isNull(Kind::getDeletedAt)
                .one();
        if (Objects.isNull(mid)) {
            Kind kind = new Kind();
            kind.setType(type);
            kind.setCreatedAt(LocalDateTime.now());
            kindService.save(kind);
        } else {
            throw new DefaultException("该种类已存在，请勿重复添加");
        }

    }

    @Override
    public List<MessageBoardVo> likeLeaderBoard() throws Exception {
        Set<Integer> set = redisTemplate.opsForZSet().reverseRange(RedisEnum.MESSAGE_LIKES.getRedis(), 0, 9);
        supplyRedisMessage(set);
        removeInvisibleMessageId(set);
        List<Message> list = this.lambdaQuery()
                .select(Message::getId, Message::getTitle)
                .in(Message::getId, set)
                .isNull(Message::getDeletedAt)
                .list();
        list.forEach(message -> {
            Integer rank = redisTemplate.opsForZSet().score(RedisEnum.MESSAGE_LIKES.getRedis(), message.getId()).intValue();
            message.setLikeCount(rank);
        });
        List<Message> collect = list.stream()
                .sorted(Comparator.comparing(Message::getLikeCount).reversed())
                .collect(Collectors.toList());
        return messageConvert.toMessageBoardVo(collect);
    }

    @Override
    public void deleteKind(String name) throws Exception {
        String userId = CheckUtil.checkLogin();
        User user = userService.getById(userId);
        if (!user.getOrganizationId().equals(OrganizationEnum.administrators.getOrganizationId())
                && !user.getOrganizationId().equals(OrganizationEnum.school.getOrganizationId())) {
            throw new DefaultException("没有权限");
        }
        Kind kind = kindService.lambdaQuery()
                .select(Kind::getId)
                .eq(Kind::getType, name)
                .one();
        Optional.ofNullable(kind).orElseThrow(() -> new DefaultException("不存在该种类"));
        kindService.removeById(kind.getId());
    }

    @Override
    public List<MessageSoaringVo> likeSoaring() throws Exception {
        Set<Integer> newRange = redisTemplate.opsForZSet().range(RedisEnum.MESSAGE_LIKES.getRedis(), 0, -1);
        supplyRedisMessage(newRange);
        removeInvisibleMessageId(newRange);
        Map<Integer, Integer> newMap = new HashMap<>(newRange.size());
        newRange.forEach(k -> {
            newMap.put(k, redisTemplate.opsForZSet().score(RedisEnum.MESSAGE_LIKES.getRedis(), k).intValue());
        });
        Set<Integer> oldRange = redisTemplate.opsForZSet().range(RedisEnum.MESSAGE_LIKE_HISTORY.getRedis(), 0, -1);
        Map<Integer, Integer> oldMap = new HashMap<>(oldRange.size());
        oldRange.forEach(k -> {
            oldMap.put(k, redisTemplate.opsForZSet().score(RedisEnum.MESSAGE_LIKE_HISTORY.getRedis(), k).intValue());
        });
        ArrayList<MessageSoaringVo> collect = new ArrayList<>(newMap.size());
        newMap.forEach((k, v) -> {
            MessageSoaringVo vo = new MessageSoaringVo();
            vo.setId(Integer.valueOf(k));
            vo.setLikeCount(v.intValue());
            vo.setIncreaseCount(v - Optional.ofNullable(oldMap.get(k)).orElse(0));
            collect.add(vo);
        });
        List<MessageSoaringVo> res = collect.stream()
                .sorted(Comparator.comparing(MessageSoaringVo::getIncreaseCount)
                        .reversed())
                .limit(10)
                .collect(Collectors.toList());
        List<Integer> collect1 = res.stream().map(MessageSoaringVo::getId).collect(Collectors.toList());
        Map<Integer, String> map = this.lambdaQuery()
                .select(Message::getId, Message::getTitle)
                .in(Message::getId, collect1)
                .isNull(Message::getDeletedAt)
                .list().stream().collect(Collectors.toMap(Message::getId, Message::getTitle));
        res.forEach(k->{
            Optional.ofNullable(map.get(k.getId())).ifPresent(mid->{
                k.setTitle(mid);
            });
        });
        return res;
    }

    @Override
    public void refreshHistoryCount() {
        redisTemplate.delete(RedisEnum.MESSAGE_LIKE_HISTORY.getRedis());
        Set set = redisTemplate.opsForZSet().rangeWithScores(RedisEnum.MESSAGE_LIKES.getRedis(), 0, -1);
        redisTemplate.opsForZSet().add(RedisEnum.MESSAGE_LIKE_HISTORY.getRedis(), set);
    }

    @Override
    public List<String> preview(List<MultipartFile> files) throws DefaultException {
        CheckUtil.checkImageType(files);
        return ossUtil.updateMessageImageUrl(files);
    }

    @Override
    public MessageVo getMessage(Integer id) {
        Message message = this.getById(id);
        MessageVo messageVo = messageConvert.toMessageVo(message);
        List<MessageLinkKind> list = messageLinkKindService.lambdaQuery()
                .select(MessageLinkKind::getId)
                .eq(MessageLinkKind::getMessageId, id)
                .list();
        List<Integer> collect = list.stream().map(MessageLinkKind::getId).collect(Collectors.toList());
        messageVo.setKinds(collect);
        User user = userService.lambdaQuery()
                .select(User::getName, User::getImageUrl)
                .eq(User::getId, message.getUserId())
                .one();
        Optional.ofNullable(user).ifPresent(k->{
            messageVo.setName(user.getName());
            messageVo.setUserImageUrl(user.getImageUrl());
        });
        UserLikeMessage one = userLikeMessageService.lambdaQuery()
                .select(UserLikeMessage::getStatus)
                .eq(UserLikeMessage::getUserId, message.getUserId())
                .eq(UserLikeMessage::getMessageId, id)
                .one();
        Optional.ofNullable(one).ifPresent(k-> messageVo.setLikeStatus(one.getStatus()));
        return messageVo;
    }

    /**
     * 飙升榜和排行榜补充redis信息
     *
     * @param set 信息id
     */
    public void supplyRedisMessage(Set<Integer> set) {
        if (CollectionUtils.isEmpty(set)) {
            List<Message> list = this.lambdaQuery()
                    .select(Message::getId, Message::getLikeCount)
                    .isNull(Message::getDeletedAt)
                    .list();
            list.forEach(k -> {
                redisTemplate.opsForZSet().add(RedisEnum.MESSAGE_LIKES.getRedis(), k.getId(), k.getLikeCount());
            });
            List<Integer> collect = list.stream().map(Message::getId).collect(Collectors.toList());
            set.addAll(collect);
        }
    }

    /**
     * 去除不可见的新闻id
     *
     * @param set 新闻id集合
     * @throws Exception 异常
     */
    public void removeInvisibleMessageId(Set<Integer> set) throws Exception {
        String userId = CheckUtil.checkLogin();
        User user = userService.getById(userId);
        if (user.getOrganizationId().equals(OrganizationEnum.administrators.getOrganizationId())
                || user.getOrganizationId().equals(OrganizationEnum.school.getOrganizationId())) {
            return;
        }
        List<Integer> collect1 = messageLinkUserService.lambdaQuery()
                .select(MessageLinkUser::getMessageId)
                .eq(MessageLinkUser::getUserId, userId)
                .list().stream().map(MessageLinkUser::getMessageId).distinct().collect(Collectors.toList());
        Iterator<Integer> iterator = set.iterator();
        while (iterator.hasNext()) {
            Integer next = iterator.next();
            if (!collect1.contains(next)) {
                iterator.remove();
            }
        }
    }

    public void cancelUserLikeMessage(Integer messageId, String userId) throws DefaultException {
        Boolean member = redisTemplate.opsForSet().isMember(RedisEnum.USER_LIKE_MESSAGE.getRedis() + messageId, userId);
        if (!member) {
            UserLikeMessage userLikeMessage = userLikeMessageService.lambdaQuery()
                    .select(UserLikeMessage::getStatus)
                    .eq(UserLikeMessage::getMessageId, messageId)
                    .eq(UserLikeMessage::getUserId, userId)
                    .one();
            if (Objects.isNull(userLikeMessage) || userLikeMessage.getStatus() == 0) {
                throw new DefaultException("你未点赞该条信息，无需取消");
            }
        }
        redisTemplate.opsForSet().remove(RedisEnum.USER_LIKE_MESSAGE.getRedis() + messageId.toString(), userId);

        Long rank = redisTemplate.opsForZSet().rank(RedisEnum.MESSAGE_LIKES.getRedis(), messageId);
        if (Objects.isNull(rank)) {
            Message message = messageService.lambdaQuery()
                    .select(Message::getLikeCount)
                    .eq(Message::getId, messageId)
                    .isNull(Message::getDeletedAt)
                    .one();
            if (Objects.isNull(message)) {
                throw new DefaultException("没有该信息");
            }
            redisTemplate.opsForZSet().add(RedisEnum.MESSAGE_LIKES.getRedis(), messageId, message.getLikeCount());
        }
        redisTemplate.opsForZSet().incrementScore(RedisEnum.MESSAGE_LIKES.getRedis(), messageId, -1);
        Map<String, String> map = new HashMap<>(3);
        map.put("operation", MqOperationEnum.unLikeOperation.toString());
        map.put("messageId", messageId.toString());
        map.put("userId", userId);

        rabbitTemplate.convertAndSend(RabbitMQConfig.RABBITMQ_DEMO_DIRECT_EXCHANGE, RabbitMQConfig.RABBITMQ_DEMO_DIRECT_ROUTING, map);


    }

    /**
     * 操作用户-信息点赞关系表(点赞)
     *
     * @param messageId 信息id
     * @param userId 用户id
     * @throws DefaultException 异常
     */
    public void operateUserLikeMessage(Integer messageId, String userId) throws DefaultException {
        Boolean member = redisTemplate.opsForSet().isMember(RedisEnum.USER_LIKE_MESSAGE.getRedis() + messageId, userId);
        if (Boolean.TRUE.equals(member)) {
            throw new DefaultException("你已经点赞，请勿重复点赞");
        }
        UserLikeMessage userLikeMessage = userLikeMessageService.lambdaQuery()
                .select(UserLikeMessage::getStatus)
                .eq(UserLikeMessage::getMessageId, messageId)
                .eq(UserLikeMessage::getUserId, userId)
                .one();
        if (!Objects.isNull(userLikeMessage) && userLikeMessage.getStatus() == 1) {
            redisTemplate.opsForSet().add(RedisEnum.USER_LIKE_MESSAGE.getRedis() + messageId, userId);
            throw new DefaultException("你已经点赞，请勿重复点赞");
        }
        redisTemplate.opsForSet().add(RedisEnum.USER_LIKE_MESSAGE.getRedis() + messageId, userId);
        Long rank = redisTemplate.opsForZSet().rank(RedisEnum.MESSAGE_LIKES.getRedis(), messageId);
        if (Objects.isNull(rank)) {
            Message message = messageService.lambdaQuery()
                    .select(Message::getLikeCount)
                    .eq(Message::getId, messageId)
                    .isNull(Message::getDeletedAt)
                    .one();
            if (Objects.isNull(message)) {
                throw new DefaultException("没有该信息");
            }
            redisTemplate.opsForZSet().add(RedisEnum.MESSAGE_LIKES.getRedis(), messageId, message.getLikeCount());
        }
        redisTemplate.opsForZSet().incrementScore(RedisEnum.MESSAGE_LIKES.getRedis(), messageId, 1);
        Map<String, String> map = new HashMap<>(3);
        map.put("operation", MqOperationEnum.likeOperation.toString());
        map.put("messageId", messageId.toString());
        map.put("userId", userId);

        rabbitTemplate.convertAndSend(RabbitMQConfig.RABBITMQ_DEMO_DIRECT_EXCHANGE, RabbitMQConfig.RABBITMQ_DEMO_DIRECT_ROUTING, map);
    }

    private void checkPower(String userId, List<Integer> messageIds) throws DefaultException {
        User user = userService.getById(userId);
        if (user.getOrganizationId() == OrganizationEnum.administrators.getOrganizationId()
                || user.getOrganizationId() == OrganizationEnum.school.getOrganizationId()) {
            return;
        }
        List<Message> list = this.lambdaQuery()
                .select(Message::getUserId)
                .in(Message::getId, messageIds)
                .list();
        List<String> collect = list.stream()
                .map(Message::getUserId)
                .collect(Collectors.toList());
        List<String> collect1 = collect.stream()
                .filter(k -> !k.equals(userId))
                .collect(Collectors.toList());
        if (collect1.size() > 0) {
            throw new DefaultException("没有权限");
        }
    }

    public void doDelete(List<Integer> messageIds) {
        messageLinkKindService.lambdaUpdate()
                .in(MessageLinkKind::getMessageId, messageIds)
                .remove();
        messageLinkUserService.lambdaUpdate()
                .in(MessageLinkUser::getMessageId, messageIds)
                .remove();
        messageService.lambdaUpdate()
                .set(Message::getDeletedAt, LocalDateTime.now())
                .in(Message::getId, messageIds)
                .update();
    }


    public void saveMessage(Message message) throws DefaultException {
        boolean save1 = messageService.save(message);
        if (!save1) {
            throw new DefaultException("发送信息失败");
        }
    }

    public void saveMessageLinkKind(MessageDto messageDto, Message message) throws DefaultException {
        List<Integer> kinds = messageDto.getKinds();
        List<MessageLinkKind> collect = kinds.stream().map(kind -> {
            MessageLinkKind mid = new MessageLinkKind();
            mid.setMessageId(message.getId());
            mid.setKind(kind);
            return mid;
        }).collect(Collectors.toList());
        boolean b = messageLinkKindService.saveBatch(collect);
        if (!b) {
            throw new DefaultException("发送信息失败");
        }
    }

    /**
     * 补充可见用户
     *
     * @param messageDto 发布信息dto
     * @param message    信息实体
     * @throws DefaultException 异常
     */
    public void saveMessageLinkUser(MessageDto messageDto, Message message) throws DefaultException {
        List<String> idList = userService.lambdaQuery()
                .select(User::getId)
                .notIn(!CollectionUtils.isEmpty(messageDto.getUserIds()), User::getId, messageDto.getUserIds())
                .isNull(User::getDeletedAt)
                .list().stream().map(User::getId).distinct().collect(Collectors.toList());
        List<MessageLinkUser> collect = idList.stream().map(k -> {
            MessageLinkUser messageLinkUser = new MessageLinkUser();
            messageLinkUser.setUserId(k);
            messageLinkUser.setMessageId(message.getId());
            return messageLinkUser;
        }).collect(Collectors.toList());
        boolean b = messageLinkUserService.saveBatch(collect);
        if (!b) {
            throw new DefaultException("发送信息失败");
        }
    }

    /**
     * 过滤MessageDto中的敏感信息
     *
     * @param messageDto 发布信息dto
     */
    public void filterMessageDto(MessageDto messageDto) throws JsonProcessingException {
        messageDto.setTitle(sensitiveWordFilterService.filter(messageDto.getTitle()));
        messageDto.setContent(sensitiveWordFilterService.filter(messageDto.getContent()));
    }

}




